package com.runa.rccprotocol.analysis.debao;

import com.alibaba.fastjson.JSON;
import com.runa.monitor.comm.dto.newComm.HotMeterVO;
import com.runa.persistence.service.LogService;
import com.runa.protocol.analysis.ShellBufferAnalysis;
import com.runa.protocol.dto.DtuReport;
import com.runa.protocol.dto.IInterData;
import com.runa.protocol.enums.ByteOrder;
import com.runa.protocol.util.ByteUtil;
import com.runa.rccprotocol.dto.debao.DeBaoReportAck;
import com.runa.rccprotocol.dto.runa.RunaConcenAffirmDeny;
import com.runa.rccprotocol.dto.runa.RunaConcenResponseData;
import lombok.extern.slf4j.Slf4j;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
public class DeBaoAnalysis extends ShellBufferAnalysis<byte[]> {


    public DeBaoAnalysis() {
        super(null, 0);
    }

    @Override
    public int fill(byte[] data, int size,String n) {
        LogService.saveErrorLog("德宝", "DB", data, size);
        if (size < 6) {
            return -1;
        }
        int begin;
        for (begin = 0;begin < size;begin++) {
            if ((data[begin]&0xff) == 0x68
                    && data[begin+5] == 0x68) {
                break;
            }
        }
        int L = (((data[begin+1]&0xff)) + (data[begin+2]<<8)) >> 2;
        if (size < L + 8) {
            return -1;
        }
        if ((data[begin+6+L] != ByteUtil.sum(data, 6, L))){
            return -1;
        }
        int type = data[begin + 6] & 0xff;
        switch (type) {
            //注册包或者心跳包
            case 0xC9:
                no(data);
                DtuReport dtuReport = new DtuReport(netEquNo);
                dtuReport.setMustAck(true);
                dtuReport.setAck(new DeBaoReportAck(netEquNo));
                this.interData = dtuReport;
                break;
            case 0x88:
                if ((data[begin + 21] & 0xff) ==0x68 && (data[begin + 22] & 0xff) ==0x25){
                    no(data);
                    HotMeterVO meterData = new HotMeterVO();
                    handleMeterData(data, begin, meterData);
                }
            default:
        }
        return 0;
    }

    private void no(byte[] data) {
        String a1= ByteUtil.bcd2str(data, 7, 2, false);
        short a2=ByteUtil.byteToShort(data, 7 + 2, ByteOrder.BA);
        netEquNo = String.format("%05d", a2)+a1;
    }

    private void handleMeterData(byte[] data, int index, HotMeterVO meterData) {
        index += 23;
        String serialNo = ByteUtil.bcd2str(data, index, 4, false);//待确认
        index += 7;
        meterData.setMeterSerial(serialNo);
        int ctrl = data[index++] & 0xff;
//        int DI = ((data[index++] & 0xff) << 8) | data[index++];
        int ser = data[index++];
        index+=2;
        if (ctrl != 0x81) {
            interData = new RunaConcenAffirmDeny(serialNo, false);
            return;
        }
        //结算日热量
        ++index;
        double theCurrentHeat = ByteUtil.bcdToInt(data, index, 4, false) * 0.01;
        index+=4;
        //当前热量(总热量).
        ++index;
        double theCurrentHeatSum = ByteUtil.bcdToInt(data, index, 4, false) * 0.01;
        meterData.setAccHeat((float) theCurrentHeatSum);
        index+=4;
        //热功率
        ++index;
        double thermalPower = ByteUtil.bcdToInt(data, index, 4, false) * 0.01;
        meterData.setPower( (float) thermalPower);
        index+=4;
        //瞬时流量
        ++index;
        double instantaneousDelivery = ByteUtil.bcdToInt(data, index, 4, false) * 0.0001;
        meterData.setFlow( (float) instantaneousDelivery);
        index+=4;
        //累计流量
        ++index;
        double cumulativeDischarge = ByteUtil.bcdToInt(data, index, 4, false) * 0.01;
        meterData.setAccFlow( (float) cumulativeDischarge);
        index+=5;
        //进水温
        double intoTheWater = ByteUtil.bcdToInt(data, index, 3, false) * 0.01;
        meterData.setSupplyTemp( (float) intoTheWater);
        index+=3;
        //回水温度
        double returnWaterTemperature = ByteUtil.bcdToInt(data, index, 3, false) * 0.01;
        meterData.setReturnTemp( (float) returnWaterTemperature);
        index+=3;

        //无单位,累计工作时间
        int openTime = ByteUtil.bcdToInt(data, index, 3, false);
        meterData.setWorkTime(openTime);
        index+=3;
        try {
            meterData.setMeterDate((new SimpleDateFormat("yyyyMMddHHmmss").parse(ByteUtil.bcd2str(data, index, 7, false))));
        } catch (ParseException e) {
            
        }
        meterData.setReadDate(new Date());
        RunaConcenResponseData responseData = new RunaConcenResponseData();
        responseData.addRepData(meterData);
        interData = responseData;
    }

    public static void main(String[] args) {
        DeBaoAnalysis analysis = new DeBaoAnalysis();
        String heart = "683200320068C99113972802027000000100A116".replace(" ", "");
//        String heart = "68 32 00 32 00 68 C9 01 10 11 27 00 02 7E 00 00 04 00 96 16".replace(" ", "");
        String heatMeter = "682A012A01688801101127021065000001001F3B00682584750720001111812E1F90000000000005992969100500000000170000000035376291002C263000263000231511083215120723200000B4162116".replace(" ", "");
        byte[] bytes = ByteUtil.hexStringToByte(heatMeter);
//        byte[] bytes = s.getBytes();
        analysis.fill(bytes, bytes.length,"");
        IInterData gain = analysis.gain();
        System.out.println(JSON.toJSONString(gain));

        String s = "683200320068C90110112700027C000004009416";
        byte[] b1 = ByteUtil.hexStringToByte(s);
        analysis.no(b1);

//        int i = DigitalUtil.calcCrc16(ByteUtil.hexStringToByte("7E 0D 68 34 20 11 10 0F 1E 07 12 A5 5A D8 8D 7E".replace(" ","")), 1, 12);
//        int i = DigitalUtil.CRC16_XMODEM(ByteUtil.hexStringToByte("0D 68 34 20 11 10 0F 1E 07 12 A5 5A"));
//        System.out.println(i);
    }
}
